<template>
  <div class="content">
    <div class="cloud-header">
      <h2 class="r-title-h2">商品管理</h2>
    </div>
    <div class="cloud-body">
      <Screen :list="search_config" :data="search_data" @submit="onSearch"></Screen>
    </div>
    <div class="cloud-body">
      <div class="r-table">
        <div class="r-table-head">
          <div class="r-table-title"><i class="iconfont icon-menu1"></i>商品列表</div>
          <div class="r-table-button">
            <button class="h-btn h-btn-text-primary" @click="toAddGoods"><i class="iconfont icon-add"></i>新增商品</button>
            <button class="h-btn h-btn-text-primary" @click="toRecycleBin"><i class="iconfont icon-delete8e"></i>回收站</button>
          </div>
        </div>
        <Table :datas="datas" class="r-table-main" @select="onselect" :checkbox="checkbox" :stripe="stripe" :loading="loading" selectWhenClickTr>
          <TableItem title="" prop="$serial" v-if="serial"></TableItem>
          <TableItem title="商品名称" prop="name" :width="180"></TableItem>
          <TableItem align="center" title="产品图" prop="image" :width="100">
            <div slot-scope="{data}" class="r-table-img">
              <img :src="data.image_list[0]">
            </div>
          </TableItem>
          <TableItem align="center" title="是否上架">
            <div slot-scope="{data}">
              {{data.putaway == 1 ? '上架' : '下架'}}
            </div>
          </TableItem>
          <TableItem title="单价（元）" prop="price" :width="120" align="center"></TableItem>
          <TableItem title="折扣" prop="price_discount" align="center"></TableItem>
          <TableItem title="分类" :width="80">
            <div slot-scope="{data}">
              {{ intCleck(data.classify_id) }}
            </div>
          </TableItem>
          <TableItem title="上传时间" prop="creation_time" :width="200" align="center"></TableItem>
          <TableItem title="操作" align="center" :width="160">
            <template slot-scope="{data}">
              <div class="r-item-action">
                <div @click="intEdit(datas, data)" class="r-action-button">编辑</div>
                <div @click="intRemove(datas, data)" class="r-action-button">加入回收站</div>
              </div>
            </template>
          </TableItem>
          <div slot="empty">暂时还没有商品哦！</div>
        </Table>
        <div class="r-table-footer">
          <div>
            <button @click="intRemove(datas, batch_val)" class="h-btn h-btn-no-border h-btn-text-blue">批量加入回收站</button>
          </div>
          <div>
            <Pagination v-model="pagination" @change="currentChange" :small="true" layout="total,pager,jumper"></Pagination>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script type="text/javascript">
//搜索组件
import Screen from '@/components/screen'
export default {

  name: "",
  data() {
    return {
      datatable_name: 'goods',


      batch_val: [],

      /**
       * 搜索数据
       * @type {[type]}
       */
      search_config: [{
          type: 'select',
          label: '选择状态',
          name: 'putaway',
          titleName: 'label',
          keyName: 'value',
          option: [{
            label: '全部',
            value: 'all'
          }, {
            label: '上架',
            value: 1,
          }, {
            label: '下架',
            value: 0
          }]
        },
        {
          type: 'input',
          label: '输入搜索',
          name: 'name',
          placeholder: '输入商品标题'
        },
        {
          type: 'date',
          min_name: 'startDate',
          max_name: 'endDate',
          label: '上传时间',
          format: 'YYYY-MM-DD',
          model: 'range', //模式
        }
      ],
      search_data: {
        name: '',
        startDate: '',
        endDate: '',
        putaway: '',
        _uniqueid: '',
        deleted: 1
      },

      // 表格
      show: false,
      border: false,
      stripe: false,
      checkbox: true,
      serial: false,
      loading: true,
      datas: [],

      // 分页
      pagination: {
        page: 1,
        size: 10,
        total: 0
      },
      dataOption: [],
    }
  },
  components: {
    Screen
  },
  mounted() {

    this.search_data._uniqueid = this.$cloud.userInfo()._uniqueid

    this.getList();

    this.getClassify();

    this.getTotal();
  },
  methods: {
    /**
     * 获取数据总数
     */
    async getTotal() {
      let ret = await this.$cloud.name(this.datatable_name).where(this.search_data).count();
      this.pagination.total = ret;
    },

    /**
     * 获取商品列表
     * @return {[type]} [description]
     */
    async getList() {
      this.loading = true;
      let ret = await this.$cloud.name(this.datatable_name).where(this.search_data).page(this.pagination.page, this.pagination.size).select();
      if (ret) {
        this.loading = false;
        this.datas = ret;

        console.log('ret', ret);
      } else {
        this.loading = false;
        this.$Message.error('网络异常，请稍后重试！')
      }
    },

    /**
     * 显示商品分类
     * @param  {[type]} id [description]
     * @return {[type]}    [description]
     */
    intCleck(id) {
      for (let key in this.dataOption) {
        if (this.dataOption[key]['_id'] == id) {
          return this.dataOption[key]['name'];
        }
      }
    },

    /**
     * 获取商品分类列表
     * @return {[type]} [description]
     */
    async getClassify() {
      let ret = await this.$cloud.name('goods_classify').select();
      if (ret || ret.length == 0) {
        this.dataOption = ret;
        // this.loading = false;
      } else {
        this.$Message.error('网络异常，请稍后重试！')
      }
    },

    // 跳转到新增商品
    toAddGoods() {
      this.$router.push('/product/releaseProduct');
    },

    toRecycleBin() {
      this.$router.push('/product/pRecycleBin');
    },

    /**
     * 筛选数据
     * @param  {[type]} data [description]
     * @return {[type]}      [description]
     */
    async onSearch(data) {
      if (data.putaway == 'all') {
        delete data.putaway
      }
      data['deleted'] = 1;

      if (data.startDate && data.endDate) {
        data['creation_time'] = ['>', data.startDate, '<', data.endDate]
      }
      this.search_data = data;
      this.pagination.page = 1;

      //重新获取数据
      await this.getTotal();
      await this.getList();
    },




    onselect(data) {
      this.batch_val = data;
    },

    /**
     * 商品编辑更新
     * @param  {[type]} datas [description]
     * @param  {[type]} data  [description]
     * @return {[type]}       [description]
     */
    intEdit(datas, data) {
      // console.log('data',data);
      this.$router.push({
        path: '/product/releaseProduct',
        query: { id: data._id }
      })
    },

    /**
     * 加入回收站
     * @param  {[type]} datas [description]
     * @param  {[type]} data  [description]
     * @return {[type]}       [description]
     */
    async intRemove(datas, data) {
      let _id = [];
      if (Object.prototype.toString.call(data) == '[object Array]') {
        if (data.length == 0) {
          this.$Message.error('请选中要删除的商品！')
          return false;
        }
        for (let key in data) {
          _id.push(data[key]['_id'])
        }
      } else {
        _id.push(data._id);
      }

      //加入回收站
      let ret = this.$cloud.name(this.datatable_name).where({ _id: ['in', _id] }).update({ deleted: 0 });
      if (ret) {
        //重新获取数据
        await this.getTotal();
        await this.getList();
        this.$Message.success('加入回收站成功！');
      } else {
        this.$Message.error('网络异常，请稍后重试！')
      }
      // datas.splice(datas.indexOf(data), 1);
    },


    /**
     * 分页功能
     * @param  {[type]} value [description]
     * @return {[type]}       [description]
     */
    async currentChange(value) {
      this.pagination = value;

      //重新获取数据
      await this.getTotal();
      await this.getList();
    }
  }
}

</script>
<style type="text/css" lang="less" scoped="scoped">
.cloud-header {
  margin-bottom: 20px;
}

.r-title-h2 {
  border-left: solid 5px #2d7bf4;
  padding-left: 10px;
  margin-bottom: 0px !important;
}

.r-table {
  .r-table-head {
    border-bottom: solid 1px #efefef;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-bottom: 20px;

    .r-table-title {
      color: #999;

      i {
        margin-right: 10px;
      }
    }

    .r-table-button {
      button {
        margin-left: 15px;
      }

      i {
        margin-right: 5px;
      }
    }
  }

  .r-table-main {
    border: none;

    th {
      background-color: #fff;
    }

    .r-table-img {
      width: 80px;
      height: 80px;
      border: solid 1px #efefef;
      margin-right: 0px;
      display: flex;
      justify-content: center;
      align-items: center;

      img {
        width: auto;
        height: auto;
        max-width: 100%;
        max-height: 100%;
      }
    }
  }

  .r-item-action {
    display: flex;
    align-items: center;
    justify-content: center;

    .r-action-button {
      margin: 0px 5px;
      color: #3788ee;
      cursor: pointer;
    }

    .r-action-button:active {
      color: #2677dd;
    }
  }

  .r-table-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    align-items: center;
    padding-top: 20px;
    margin-top: 20px;
    border-top: 1px solid #eeeeee;
  }
}

</style>
